import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import {
  Card, Table, Modal, Form,
  Input, Button, Icon, InputNumber,
  Upload, Row, Col, Divider, Select, Spin,
  TreeSelect, message
} from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './UserManagement.less';
import { validatemobile } from '../../utils/utils';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option, OptGroup } = Select;
const TreeNode = TreeSelect.TreeNode;

let userState = ["停用", "启用"];

@connect(({ user1, }) => ({
  user1,
}))
@Form.create()
export default class ProductManagement extends Component {
  state = {
    isAdd: true,
    previewVisible: false,
    previewImage: '',
    fileList: [],
    userId: '',
    parentId: '',
    jobsId: '',
    branchValue: '',
    positionNameValue: '',
    userName: '',
    userNameBlur: '',
    name: '',
    postId: '',
    userDetails: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'user1/fetch',
      payload: { offset: 0, limit: 10 },
      // callback: (response) => {
      //   this.setState({
      //     organizationList: response,
      //   })
      // },
    });

    dispatch({
      type: 'user1/getBranchTreeList',
      payload: {
      }
    })
  }

  handleStandardTableChange = (e) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'user1/fetch',
      payload: {
        offset: (e.current - 1) * e.pageSize,
        limit: e.pageSize,
        name: this.state.name,
        userName: this.state.userName
      },
    });
    // dispatch({
    //   type: 'user1/fetch',
    //   payload: { offset: (e.current - 1) * e.pageSize, limit: e.pageSize },
    // });
  }

  // componentWillUnmount() { }

  add = () => {
    this.setState({ isAdd: true })
    this.props.dispatch({
      type: 'user1/showEdit',
      payload: true,
    })
  }

  edit = (record) => {
    // console.log()
    this.setState({
      isAdd: false,
      userId: record.id,
      userDetails: record
    })

    this.props.dispatch({
      type: 'user1/showEdit',
      payload: true,
    })
    this.props.dispatch({
      type: 'user1/setValue',
      payload: record,
    })
  }

  onCancel = () => {
    // this.props.form.resetFields();
    this.props.dispatch({
      type: 'user1/showEdit',
      payload: false,
    })
  }

  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }

  handleChange = ({ fileList }) => this.setState({ fileList })

  handleSearch = () => {
    const { validateFieldsAndScroll } = this.props.form;

    validateFieldsAndScroll((error, values) => {
      if (!error) {
        // console.log("qqqqqq")
        // console.log(values)
        this.props.dispatch({
          type: 'user1/fetch',
          payload: values,
        })
        this.props.form.resetFields();
      }
    });
  };

  hanleCreateUserModalOk = () => {
    const { validateFieldsAndScroll } = this.props.form;
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        if (this.state.isAdd) {
          this.props.form.resetFields();
          this.props.dispatch({
            type: 'user1/add',
            payload: {
              employeeNum: values.employeeNum,
              userName: values.userName,
              name: values.name,
              phone: values.phone,
              branchId: this.state.branchValue,
              postId: this.state.jobsId,
            },
            callback: () => {
              this.props.dispatch({
                type: 'user1/fetch',
                payload: {
                  offset: 0,
                  limit: 10,
                },
              });
            },
          });
        } else {
          this.props.form.resetFields();
          this.props.dispatch({
            type: 'user1/update',
            payload: {
              id: this.state.userId,
              employeeNum: values.employeeNum,
              userName: values.userName,
              name: values.name,
              phone: values.phone,
              branchId: this.state.branchValue,
              postId: this.state.jobsId,

            },
            callback: () => {
              this.props.dispatch({
                type: 'user1/fetch',
                payload: {
                  offset: 0,
                  limit: 10,
                },
              });
            },
          });
        }
      }
    });
  };

  handleSetState = (record, newState) => {
    this.props.dispatch({
      type: 'user1/changeUserState',
      payload: {
        id: record.id,
        state: newState
      },
      callback: () => {
        this.props.dispatch({
          type: 'user1/fetch',
          payload: {
            offset: 0,
            limit: 10,
          },
        });
      },
    });
  }

  handleBranchChange = (value) => {
    this.setState({
      parentId: value,
    })
  }

  handleJobsChange = (value) => {
    this.setState({
      jobsId: value,
      positionNameValue: value
    })

  }

  renderOption = (data) => {
    const options = [];
    data.map((item) => {
      options.push(<Option value={item.id}>{item.positionName}</Option>)
    })
    return options;
  }

  handleChangePassword = (record) => {
    // console.log("AADAFAFArecord")
    // console.log(record.id)
    this.props.dispatch({
      type: 'user1/changePassword',
      payload: {
        userId: record.id,
      },
      callback: () => {
        this.props.dispatch({
          type: 'user1/fetch',
          payload: {
            offset: 0,
            limit: 10,
          },
        });
      },
    });
  }

  hanleTreeSelectChange = (value, info) => {
    this.setState({
      branchValue: value,
      jobsId: '',
      userDetails: {
        ...this.state.userDetails,
        positionName: '',
      }
    })

    this.props.dispatch({
      type: 'user1/getPostListByBranchId',
      payload: {
        branchId: value
      },
    });
  }

  handleGetUserName = (e) => {
    this.setState({
      userName: e.target.value,
    })
  }

  handleGetName = (e) => {
    this.setState({
      name: e.target.value,
    })
  }

  // wrapTreeDataRecord = (list) => {
  //   if (list) {
  //     return list.map((item) => {
  //       if (item.children) {
  //         return (
  //           <TreeNode
  //             title={item.orgName}
  //             value={item.id}
  //             key={item.id}
  //             dataRef={item}
  //           >
  //             {this.wrapTreeDataRecord(item.children)}
  //           </TreeNode>
  //         ); 
  //       }
  //       return <TreeNode
  //         value={item.id}
  //         dataRef={item}
  //         key={item.id}
  //         title={item.orgName} />
  //     });
  //   }
  // }

  wrapTreeDataRecord = (record) => {
    return (
      <TreeNode
        title={record.orgName}
        value={record.id}
        key={record.id}
        dataRef={record}
      >
        {
          record.children && record.children.length > 0 && record.children.map((item) => {
            return this.wrapTreeDataRecord(item)
          })
        }
      </TreeNode>
    );
  }


  columns = [{
    //   title: '工号',
    //   dataIndex: 'employeeNum',
    //   key: 'employeeNum',
    // }, {
    //   title: '用户名',
    //   dataIndex: 'userName',
    //   key: 'userName',
    // }, {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
  }, {
    title: '联系方式',
    dataIndex: 'phone',
    key: 'phone',
  }, {
    title: '所属组织',
    dataIndex: 'orgName',
    key: 'orgName',
  }, {
    title: '岗位',
    dataIndex: 'positionName',
    key: 'positionName',
  }, {
    title: '状态',
    dataIndex: 'state',
    key: 'state',
    render(val) {
      return userState[val];
    },
  }, {
    title: '操作',
    dataIndex: 'state',
    key: 'id',
    render: (text, record) => (
      //state ：0 停用 ，  1 启用
      <Fragment>
        <a onClick={() => this.edit(record)}>编辑</a>
        <Divider type="vertical" />
        {record.state == '0' ?
          <a onClick={() => this.handleSetState(record, 1)}>启用</a>
          :
          <a onClick={() => this.handleSetState(record, 0)}>停用</a>}
        <Divider type="vertical" />
        <a onClick={() => this.handleChangePassword(record)}>重置密码</a>
      </Fragment>
    )
  }];

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      userName: '',
      name: '',
    });
    dispatch({
      type: 'user1/fetch',
      payload: {
        offset: 0,
        limit: 10,
      },
    });
  }

  handleSubmit = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'user1/fetch',
      payload: {
        offset: 0,
        limit: 10,
        name: this.state.name,
        userName: this.state.userName
      },
    });
  }

  handleBlur = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'user1/existUserName',
      payload: {
        userName: this.state.userNameBlur
      },
    });
  }

  handleValidationUserName = (e) => {
    this.setState({
      userNameBlur: e.target.value
    })
  }

  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={10} sm={24}>
            <FormItem label="用户名">
              <Input placeholder="请输入" value={this.state.userName} onChange={this.handleGetUserName} />
            </FormItem>
          </Col>
          <Col md={10} sm={24}>
            <FormItem label="姓名">
              <Input placeholder="请输入" value={this.state.name} onChange={this.handleGetName} />
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <p style={{ textAlign: 'right' }} className={styles.submitButtons}>
            <Button type="primary" onClick={this.handleSubmit} >搜索</Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
          </p>
        </Row>
      </Form>
    );
  }

  render() {
    const { isAdd, previewVisible, previewImage, fileList } = this.state;
    const { user1: { userList, page, loading, modalVisible, detailValue, confirmLoading, branchList, jobsList, branchTreeList } } = this.props;
    const { getFieldDecorator, getFieldValue, validateFieldsAndScroll } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    return (
      <PageHeaderLayout title="用户管理">
        {/* {JSON.stringify(branchTreeList)} */}
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderSimpleForm()}
            </div>

            <Button icon='plus' type="primary" style={{ marginTop: 10, marginBottom: 10 }} onClick={this.add}>添加</Button>
            <Table
              bordered
              dataSource={userList}
              columns={this.columns}
              rowKey="id"
              pagination={page}
              loading={loading}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <Modal
          title={isAdd ? '添加用户' : '编辑用户信息'}
          style={{ top: 20 }}
          visible={modalVisible}
          confirmLoading={confirmLoading}
          onOk={this.hanleCreateUserModalOk}
          onCancel={this.onCancel}>
          {/* {this.state.userDetails} */}
          <Form >
            <FormItem {...formItemLayout} label="员工号">
              {getFieldDecorator('employeeNum', {
                initialValue: isAdd ? null : detailValue.employeeNum,
                rules: [{
                  required: true, message: '请输入员工号',
                }],
              })(
                <Input placeholder="请输入员工号" />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="用户名">
              {getFieldDecorator('userName', {
                initialValue: isAdd ? null : detailValue.userName,
                rules: [{
                  required: true, message: '请输入用户名',
                }],
              })(
                <Input placeholder="请输入用户名" onChange={this.handleValidationUserName} onBlur={this.handleBlur} />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="姓名">
              {getFieldDecorator('name', {
                initialValue: isAdd ? null : detailValue.name,
                rules: [{
                  required: true, message: '请输入姓名',
                }],
              })(
                <Input placeholder="请输入姓名" />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="联系方式">
              {getFieldDecorator('phone', {
                initialValue: isAdd ? null : detailValue.phone,
                // rules: [{
                //   required: true, message: '请输入联系方式',
                // }],
              })(
                <InputNumber placeholder="请输入联系方式" style={{ width: '100%' }} />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="所属组织">
              {getFieldDecorator('orgName', {
                initialValue: isAdd ? null : detailValue.orgName,
                rules: [{
                  required: true, message: '请选择所属组织',
                }],
              })(
                <TreeSelect
                  // allowClear
                  style={{ width: '100%' }}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  placeholder="请选择所属组织"
                  placeholder="请选择"
                  treeDefaultExpandAll
                  onChange={this.hanleTreeSelectChange}
                // onSelect={this.hanleTreeSelectChange}
                >
                  {
                    branchTreeList ?
                      branchTreeList.map((item) => {
                        return this.wrapTreeDataRecord(item);
                      })
                      // this.wrapTreeDataRecord(branchTreeList) 
                      :
                      null
                  }
                </TreeSelect>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="岗位">
              {getFieldDecorator('positionName', {
                initialValue: isAdd ? null : this.state.userDetails.positionName,
                rules: [{
                  required: true, message: '请选择岗位',
                }],
              })(
                <Select
                  placeholder="请选择岗位"
                  style={{ width: '100%' }}
                  onChange={this.handleJobsChange}
                >
                  {jobsList && this.renderOption(jobsList)}
                </Select>
              )}
            </FormItem>
          </Form>
        </Modal>

      </PageHeaderLayout>
    );
  }
}
